<?php
declare(strict_types=1);

namespace app\appointment\model;

use app\common\model\AppointmentForm as AppointmentFormModel;
use app\common\enum\FormStatus as FormStatusEnum;
use app\common\model\AppealImage as AppealImageModel;
use app\api\model\UploadFile as UploadFileModel;
class AppointmentForm extends AppointmentFormModel
{
    public function add($userId, $data)
    {
         return $this->transaction(function () use ($userId, $data) {
            $data['user_id'] = $userId;
            $this->save($data);

             // 新增图片文件关联
             if(count($data['imagesId']) > 0){
                 $this->images()->attach($data['imagesId']);
             }

//            $img_data = [];
//           $AppealImageModel= new AppealImageModel;
//                foreach($data['imagesId'] as $key => $val){
//                    $img_data[$key]['appeal_id'] = $this ->appointment_id;
//                    $img_data[$key]['file_id'] = $val;
//                    $img_data[$key]['create_time'] = time();
//                }
//
//             $AppealImageModel->saveAll($img_data);
                return true;
        });
    }

    public function edit($data) {

        if($this->status === FormStatusEnum::ARRIVAL) {
            $this->error = '该诉求已终止，不可修改';
            return false;
        }

        return $this->transaction(function () use ($data) {
            $this->allowField(['secrecy', 'name', 'phone', 'address', 'detail_address', 'type', 'intro','project'])->save($data);

            //删除图片文件关联
            if(count($data['deleteImagesId']) > 0){
                $this->images()->detach($data['deleteImagesId']);
            }

            // 新增图片文件关联
            if(count($data['imagesId']) > 0){
                $this->images()->attach($data['imagesId']);
            }
//            $img_data = [];
//            $AppealImageModel= new AppealImageModel;
//            foreach($data['imagesId'] as $key => $val){
//                $img_data[$key]['appeal_id'] = $this ->appointment_id;
//                $img_data[$key]['file_id'] = $val;
//                $img_data[$key]['create_time'] = time();
//            }
//
//            $AppealImageModel->saveAll($img_data);
            return true;
        });

    }

    public function getList(array $where = [])
    {
        return $this->with(['carType'])->where($where)->order('time', 'asc')->select();
    }


    public function switchStatus($status)
    {
        // 若该预约状态为到场，则不允许修改
        if($this->status === FormStatusEnum::ARRIVAL) {
            $this->error = '该预约已签到，不可取消';
            return false;
        }
        $this->status = $status;
        return $this->save();
    }

    public function checkin()
    {
        $this->status = 20;
        return $this->save();
    }

}
